package com.yunban.project.api.text_check.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunban.project.api.text_check.domain.ThreadConfig;
import com.yunban.project.api.text_check.mapper.ThreadConfigMapper;
import com.yunban.project.api.text_check.service.ThreadConfigService;
import net.lab1024.sa.base.ProjectConstants;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author: lijiajun
 * @date: 2024-12-04
 * @version: 1.0
 */
@Service
public class ThreadConfigServiceImpl extends ServiceImpl<ThreadConfigMapper, ThreadConfig> implements ThreadConfigService {
    @Override
    public Boolean checkCurrentThreadConfig() {
        LambdaQueryWrapper<ThreadConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ThreadConfig::getCode, ProjectConstants.TEXT_CORRECTION_THREAD_CODE);
        // 已使用数量小于最大数量
        queryWrapper.last("and used_thread_count < max_thread_count");
        ThreadConfig config = this.getOne(queryWrapper);
        return !ObjectUtils.isEmpty(config);
    }

    @Override
    public Boolean useThread() {
        LambdaUpdateWrapper<ThreadConfig> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ThreadConfig::getCode, ProjectConstants.TEXT_CORRECTION_THREAD_CODE);
        updateWrapper.setSql("used_thread_count = used_thread_count + 1");
        updateWrapper.last("and used_thread_count < max_thread_count");
        return this.update(updateWrapper);
    }

    @Override
    public void releaseThread() {
        LambdaUpdateWrapper<ThreadConfig> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ThreadConfig::getCode, ProjectConstants.TEXT_CORRECTION_THREAD_CODE);
        updateWrapper.setSql("used_thread_count = used_thread_count - 1");
        updateWrapper.last("and used_thread_count > 0");
        this.update(updateWrapper);
    }
}